const app = getApp();
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function login(userInfo, that) {
  if (app.global.code) {
    console.log(userInfo);
    myRequest("https://nideshop.bluej.cn/auth/loginByWeixin", {
        appId: 'wxdaa8eb739d8a2c30',
        secret: '63e0b3512ca4aa715c33ed41003cb704',
        code: app.global.code,
        userInfo
      },
      res => {
        wx.setStorageSync('token', res.data.data.token);
        that.setData({
          token: res.data.data.token
        })
        wx.setStorageSync('userInfo', res.data.data.userInfo);
      },
      'post'
    )
  } else {
    // 拿到code
    wx.login({
      success: res => {
        app.global.code = res.code;
        // 拿到token
        myRequest("https://nideshop.bluej.cn/auth/loginByWeixin", {
            // appId: 'wxdaa8eb739d8a2c30',
            // secret: '63e0b3512ca4aa715c33ed41003cb704',
            code: app.global.code,
            userInfo
          },
          res => {
            console.log(res)
            wx.setStorageSync('token', res.data.data.token);
            that.setData({
              token: res.data.data.token
            })
          },
          'post'
        )
      }
    })
  }
}

function myRequest(url, data, success = function () {}, method = 'get') {
  wx.request({
    url,
    data,
    method,
    header: {
      'X-Nideshop-Token': wx.getStorageSync('token')
    },
    success
  });
}
module.exports = {
  formatTime: formatTime,
  myRequest,
  login
}